package main

import (
	"database/sql"
	"fmt"

	_ "github.com/go-sql-driver/mysql"
)

func main() {
	db, err := sql.Open("mysql", "root:root@/test?charset=utf8")
	if err != nil {
		fmt.Println(err)
	}

	//插入数据
	stmt, err := db.Prepare("INSERT INTO users SET name=?")
	if err != nil {
		fmt.Println(err)
	}

	res, err := stmt.Exec("小米")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(res)

	//返回id
	id, err := res.LastInsertId()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(id)

	//更新数据
	stmt, err = db.Prepare("update users set name=? where id=?")
	if err != nil {
		fmt.Println(err)
	}
	res, err = stmt.Exec("小明3", 2)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(res)

	affect, err := res.RowsAffected()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(affect)

	//查询数据
	rows, err := db.Query("SELECT * FROM users")
	if err != nil {
		fmt.Println(err)
	}

	for rows.Next() {
		var id int
		var name string

		err = rows.Scan(&id, &name)
		if err != nil {
			fmt.Println(err)
		}
		fmt.Printf("%d %s \n", id, name)
	}

	//删除数据
	// stmt, err = db.Prepare("delete from userinfo where uid=?")

}
